/*
 * Copyright (C) 2010 Young, Fey <fey.young@gmail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

package com.youngfey.chess.engine.uci
import com.youngfey.chess.engine.*
import com.youngfey.chess.*
import com.youngfey.util.logging.Logger

/**
 * Engine的UCI实现
 * @author Young, Fey <fey.young@gmail.com>
 */
class UciEngine extends Engine {
    def UciEngine(String cmd) {
        super(cmd) 
        initUci()
    }

    @Override
    boolean isReady() {
        false
    }

    @Override
    void analyze(Position position) {
    }

    @Override
    Evaluation getEvaluation() {
    }

    @Override
    void stop() {
    }

    //清除当前输出；执行uci命令；读取id/option/uciok输出
    //如果引擎未能在100毫秒完成uciok输出，则视为启动失败，
    //初始化过程中将忽略所有option输出
    private initUci() {
        input = 'uci'
        sleep 100
        while(hasOutputs) {
            def line = output
            if(line.startsWith('id')) {
                def ts = line.split()
                if(ts.size() < 3) {
                    Logger.log(Logger.WARNING, "Engine output error: $line")
                }

                switch(ts[1]) {
                    case 'name':
                    name = ts[2..-1].join(' ')
                    break
                    case 'author':
                    author = ts[2..-1].join(' ')
                    break
                }
            } else if(line == 'uciok') {
                alive = true
            }
        }

        if(!alive) {
            Logger.log(Logger.WARNING, "Engine failed")
            close()
        }
    }

    // For debug only
    @Override
    String toString() {
        "${this.class.name}$properties"
    }

    def name
    def author
}


